package com.xd.core.api.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ancun.netsign.client.NetSignClient;
import com.ancun.netsign.model.*;
import com.xd.common.constant.SysConstant;
import com.xd.common.exception.XkdException;
import com.xd.common.util.AESUtil;
import com.xd.common.util.OrderNumUtil;
import com.xd.core.api.dto.*;
import com.xd.core.api.service.ApiContractService;
import com.xd.core.api.vo.CertificationSignUrlLinkVo;
import com.xd.core.api.vo.ContractInfoVo;
import com.xd.core.business.mapper.ContractMapper;
import com.xd.core.company.entity.Company;
import com.xd.core.company.entity.CompanyContract;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Api(tags = "合同签署API")
@RestController
@RequestMapping("/contractApi")
public class ApiContractController {

    @Resource
    private ApiContractService apiContractService;

    public static void main(String[] args) {
        String apiaddr = "https://oapi.asign.cn/";
        String appid = "974822040";
        String pr = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCfw9mPLfH70QibSrVKbiuKM+w19AculiUISqsB6r5i9o7lZ7ZXu4B1rUdlzvYyXtOSKM5Z/O/Hv7HgOqiWW1EAR7uaEx1htkvE2NJbWmhNvsizRihfpbLVkMqmQ9928fhEV2PKJLikLPBBng89MHhMifburb0Zyo1A+oZDZkxm/+x/RehM8j5oiERr/NPRDZcA3cbtFLBvPM6vIU3EttcP8BmZLXdtshs6Hl+BtXOsdKuOJX3piYcMJ+Drr/V0dnyyctoAn1AiR7xZKXBId0TyOwQTH5i/mZEq+ihHWMVeBj7x0vubQ+Adh4lI2csEP7Nst8FtM/O47cf049U1nXqhAgMBAAECggEATH4m4iirXVfd+Qwx9Kr+6bKme8aU0bdNj8TAT7Cm6xcFn8yiPysk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XIdUr8mM1GbV0achugJfObs2BXAiMoup13IdQLp+iyEE/m3aqV/AUSvx3IQX8B3KRIzxX3z3QBxT/pTHAx6dQ==";
        NetSignClient netSignClient1 = new NetSignClient(apiaddr, appid, pr);
//        /*
//         * 添加陌生用户
//         * */
//        AddStrangerInput addStrangerInput = new AddStrangerInput();
//        addStrangerInput.setAccount("18912015854");
//        addStrangerInput.setUserType(2);
//        ApiRespBody<Void> voidApiRespBody = netSignClient1.addStrangerV2(addStrangerInput);
//        System.out.println(voidApiRespBody);
//
//        /*
//         * 查询用户是否认证过
//         * */
//        ApiRespBody<SignUserOutput> user = netSignClient1.getUser("123115645648888811");
//        System.out.println(user.getData().getStatus());
        ApiRespBody contractInfo = netSignClient1.getContractInfo("FM-HT202509081616554906649");
        Object data = contractInfo.getData();
        JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(data), JSONObject.class);
        String string = jsonObject.getString("signUser");
        System.out.println( string);
        List<ContractInfoVo> signUserOutputs = JSONObject.parseArray(string, ContractInfoVo.class);

        String jsonString = JSONObject.toJSONString(signUserOutputs);
        System.out.println(jsonString);
//        //生成合同
//        String contractNo = OrderNumUtil.getContractNo();
//        ContractInput contractInput = new ContractInput();
//        contractInput.setContractNo(contractNo);//合同编号
//        contractInput.setContractName("电子印章使用声明书");
//        contractInput.setValidityTime(10);//合同签署剩余天数（系统当前时间+该天数=在此日期之前可以签署合同日期）
//        contractInput.setSignOrder(1); // 签约方式，1：无序签约 2：顺序签约
//        // 生成合同模板
//        List<ContractInput.Template> templates = new ArrayList<>();
//        ContractInput.Template template = new ContractInput.Template();
//        template.setTemplateNo("TN39EC56D49E9D497B8323E28B77C3760E-2430");
//        templates.add(template);
//        contractInput.setTemplates(templates);
//        ApiRespBody<ContractOutput> contract = netSignClient1.createContract(contractInput);
//
//        //添加签署方发起合同
//        //添加签署方发起合同
//        /*
//         * 资方
//         * */
//        List<ContractUserInput> userInputList = new ArrayList<>();
//
//        /*
//         * 广东宝坤网络小额贷款有限公司
//         * */
//        ContractUserInput c2 = new ContractUserInput();
//        c2.setContractNo(contractNo);
//        c2.setAccount("ASIGN91440500MA511X440H");
//        c2.setSignType(2);//无感签约
////        c2.setSealNo(aqHtProperties.getXdSealNo());
//
//        List<UserSignStrategyInput> s2 = new ArrayList<>(5);
//        UserSignStrategyInput u2 = new UserSignStrategyInput();
//        u2.setAttachNo(1);
//        u2.setLocationMode(4);
//        u2.setSignKey("甲方");
//        s2.add(u2);
//        c2.setSignStrategyList(s2);
//        userInputList.add(c2);
//
//        //发起合同签署
//        ApiRespBody<ContractOutput> contractOutputApiRespBody = netSignClient1.addSigner(userInputList);
//        if (contractOutputApiRespBody.getCode() != 100000)
//            throw new XkdException("委托代收付协议添加签署方发起合同" + contractOutputApiRespBody.getMsg());
//
//        ContractOutput data = contractOutputApiRespBody.getData();
//        System.out.println( data);
//        ApiRespBody<DownloadContractOutput> body = netSignClient1.downloadContract("FM-HT202508071739060591669", 1, "D:\\222.pdf");

    }
    @ApiOperation(value = "查看企业是否申请印章--资方公司")
    @GetMapping("getCapitalCompanyIsAuth")
    public boolean getCapitalCompanyIsAuth(String creditCode,Integer companyId) {
        return apiContractService.getCapitalCompanyIsAuth(creditCode,companyId);
    }
    @PreAuthorize("hasAnyAuthority('sys:AssetManagement-GoAuthenticate')")
    @ApiOperation(value = "企业三要素认证")
    @GetMapping("companyAuthMobile3")
    public String companyAuthMobile3(Integer companyId) {
        return apiContractService.companyAuthMobile3(companyId);
    }

//    @PreAuthorize("hasAnyAuthority('sys:Authentication')")
    @ApiOperation(value = "投保企业三要素认证")
    @PostMapping("insuranceCompanyAuthMobile3")
    public String insuranceCompanyAuthMobile3(@RequestBody CompanyAuthMobile3Dto companyAuthMobile3Dto) {
        return apiContractService.insuranceCompanyAuthMobile3(companyAuthMobile3Dto);
    }
    /*
    * 判断企业是否添加过
    * 如果否则走认证-签章流程-投保企业/进件企业认证
    * */
    @ApiOperation(value = "查看企业是否申请印章--投保公司")
    @GetMapping("getCompanyIsAuth")
    public boolean getCompanyIsAuth(String creditCode) {
        return apiContractService.getCompanyIsAuth(creditCode);
    }
    @ApiOperation(value = "重发认证验证码")
    @GetMapping("resend")
    public void resend(String serialNo) {
        apiContractService.resend(serialNo);
    }

    @ApiOperation(value = "认证验证码校验")
    @PostMapping("verifyCaptcha")
    public void verifyCaptcha(@RequestBody VerifyCaptchaDto verifyCaptchaDto) {
        apiContractService.verifyCaptcha(verifyCaptchaDto);
    }

    @ApiOperation(value = "投保企业认证验证码校验")
    @PostMapping("insuranceVerifyCaptcha")
    public void insuranceVerifyCaptcha(@RequestBody InsuranceVerifyCaptchaDto insuranceVerifyCaptchaDto) {
        apiContractService.insuranceVerifyCaptcha(insuranceVerifyCaptchaDto);
    }
    @ApiOperation(value = "查看合同")
    @GetMapping("getContract")
    public String getContract(String contractNo) {
        return apiContractService.getContract(contractNo);
    }

    //进件的时候调用
    @ApiOperation(value = "个人信息授权使用书")
    @PostMapping("authorizationToUse")
    public void authorizationToUse(Integer id) {//进件ID
        apiContractService.authorizationToUse(id);
    }

//    //授信完成后调用
//    @ApiOperation(value = "还款承诺函")
//    @PostMapping("repaymentCommitmentLetter")
//    public void repaymentCommitmentLetter(Integer id) {//进件ID
//        apiContractService.repaymentCommitmentLetter(id,null);
//    }

    //委托划扣授权书
    //授信完成后调用  跟担保合同  抵押合同一起签署
//    @ApiOperation(value = "代扣协议")
//    @PostMapping("withhold")
//    public void withhold(Integer id) {
//        apiContractService.withhold(id,null);
//    }

    //授信完成后调用
    //签署合同--修改授信内容 自动调用
//    @ApiOperation(value = "贷款合同")
//    @PostMapping("borrowing")
//    public void borrowing(Integer id) {//进件ID
//        apiContractService.borrowing(id);
//    }

    //修改账号后调用 自动调用或者手动发起
//    @ApiOperation(value = "借款合同补充协议")
//    @PostMapping("extraBorrowing")
//    public void extraBorrowing(Integer id, String Y2bank, String Y2BankCard,Integer outId) {
//        apiContractService.extraBorrowing(id, Y2bank, Y2BankCard, outId);
//    }


    //资方注册完毕调用
    @PreAuthorize("hasAnyAuthority('sys:AssetManagement-InitiateDebtTransfer','sys:AssetManagement-Reissue')")
    @ApiOperation(value = "债权转让框架协议")
    @PostMapping("assignmentOfDebt")
    public void assignmentOfDebt(Integer companyId) {
        apiContractService.assignmentOfDebt(companyId);
    }

    //资方注册完毕调用
    @PreAuthorize("hasAnyAuthority('sys:AssetManagement-InitiateDelegationAgreement','sys:AssetManagement-Reissue')")
    @ApiOperation(value = "委托代收付协议")
    @PostMapping("wtdsfxy")
    public void wtdsf(Integer companyId) {
        apiContractService.wtdsf(companyId);
    }

    //资方注册完毕调用
    @PreAuthorize("hasAnyAuthority('sys:AssetManagement-InitiateFundingDeclarate','sys:AssetManagement-Reissue')")
    @ApiOperation(value = "资金来源合法性声明")
    @PostMapping("zjhfxsm")
    public void zjhfxsm(Integer companyId) {
        apiContractService.zjhfxsm(companyId);
    }

    //确认单
    //债权转让时自动调用或者手动发起

    @ApiOperation(value = "债权转让协议确认单")
    @PostMapping("assignmentOfDebtConfirmation")
    public void assignmentOfDebtConfirmation(Integer debtId, Integer companyId) {
        apiContractService.assignmentOfDebtConfirmation(debtId, companyId);
    }

    @PreAuthorize("hasAnyAuthority('sys:Incoming-aiaginSignContract')")
    @ApiOperation(value = "一次性签约")
    @PostMapping("signContract")
    public void signContract(@RequestBody SignContractDto signContractDto) {
        apiContractService.signContract(signContractDto);
    }
    //    @PreAuthorize("hasAnyAuthority('sys:Incoming-aiaginSignContract')")
    //公证申请
    //todo 待开发:渠道二通道上包后，修改为放款表查询通道类型
    @ApiOperation(value = "公证创建合同")
    @PostMapping("notarizationContract")
    public void notarizationContract(@RequestBody SignContractDto signContractDto) {
        apiContractService.notarizationContract(signContractDto);
    }
    //公证撤销
    @ApiOperation(value = "公证撤销")
    @PostMapping("notarizationRevocation")
    public void notarizationRevocation(@RequestParam String orderNo) {
        apiContractService.notarizationRevocation(orderNo);
    }
    //公证获取链接
    @ApiOperation(value = "公证获取链接")
    @PostMapping("getSignUrlLink")
    public List<CertificationSignUrlLinkVo> getSignUrlLink(@RequestParam String orderNo) {
        return apiContractService.getSignUrlLink(orderNo);
    }

    //还完所有资金 自动调用或者手动发起
    @PreAuthorize("hasAnyAuthority('sys:Lending-ProofSettlement')")
    @ApiOperation(value = "贷款结清证明")
    @PostMapping("dkjqzm")
    public void dkjqzm(Integer outId) {
        apiContractService.dkjqzm(outId);
    }

    //还完所有资金 自动调用或者手动发起
    @ApiOperation(value = "查询合同信息")
    @PostMapping("getContractStatus")
    public List<ContractInfoVo> getContractStatus(String contractNo) {
       return apiContractService.getContractStatus(contractNo);
    }

}
